package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/app/model"
	"FeedXmh/tdengine"
	"database/sql"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
)

var Alarm = alarm{}

type alarm struct {
}

func (a *alarm) GetAlarmNowPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	sn := gconv.String(params["sn"])
	level := gconv.String(params["level"])
	_type := gconv.String(params["type"])
	subtype := gconv.String(params["subtype"])

	alarm_content := gconv.String(params["alarm_content"])
	hnum := gconv.String(params["hnum"])

	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])

	where := " 1=1 "
	where += " and IFNULL(farmid,'')!='' "

	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if device_addr != "" {
		where += fmt.Sprintf(" and device_addr='%s'", device_addr)
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	if level != "" {
		where += fmt.Sprintf(" and level in (%s)", level)
	}
	if _type != "" {
		where += fmt.Sprintf(" and type in (%s)", _type)
	}
	if subtype != "" {
		where += fmt.Sprintf(" and subtype in (%s)", subtype)
	}
	if hnum != "" {
		where += fmt.Sprintf(" and remark='%s'", hnum)
	}

	if alarm_content != "" {
		where += " and alarm_content LIKE '%" + alarm_content + "%'"
	}

	if begin != "" {
		where += " and add_time>='" + begin + "' "
	}
	if end != "" {
		end += " 23:59:59 "
		where += " and add_time<='" + end + "' "
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	where += dao.SetPermisAddWhere(userid)
	//db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))

		model := db.Model("v_alarm_now")
		count, err := model.Where(where).Count()
		if err != nil {
			g.Log().Line().Error(err)
		} else {
			res["count"] = count
			start := limit*page - limit
			if start < 0 {
				start = 0
			}
			if order != "" {
				model = model.Order(order)
			} else {
				model = model.Order(" add_time DESC,farmname ASC,housename ASC,remark ASC ")
			}
			list, error := model.Where(where).Limit(start, limit).All()
			if error != nil {
				g.Log().Line().Error(error)
			} else {
				res["data"] = list
			}
		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *alarm) GetAlarmNow(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	order := gconv.String(params["order"])
	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	sn := gconv.String(params["sn"])
	level := gconv.String(params["level"])
	_type := gconv.String(params["type"])
	subtype := gconv.String(params["subtype"])

	alarm_content := gconv.String(params["alarm_content"])
	hnum := gconv.String(params["hnum"])

	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])

	where := " 1=1 "
	where += " and IFNULL(farmid,'')!='' "

	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if device_addr != "" {
		where += fmt.Sprintf(" and device_addr='%s'", device_addr)
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	if level != "" {
		where += fmt.Sprintf(" and level in (%s)", level)
	}
	if _type != "" {
		where += fmt.Sprintf(" and type in (%s)", _type)
	}
	if subtype != "" {
		where += fmt.Sprintf(" and subtype in (%s)", subtype)
	}
	if hnum != "" {
		where += fmt.Sprintf(" and remark='%s'", hnum)
	}

	if alarm_content != "" {
		where += " and alarm_content LIKE '%" + alarm_content + "%'"
	}

	if begin != "" {
		//add_time取日期部分对比
		where += " and add_time>='" + begin + "' "
	}
	if end != "" {
		end += " 23:59:59 "
		where += " and add_time<='" + end + "' "
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	where += dao.SetPermisAddWhere(userid)
	//db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		model := db.Model("v_alarm_now")
		if order != "" {
			model = model.Order(order)
		} else {
			model = model.Order(" add_time DESC,farmname ASC,housename ASC,remark ASC ")
		}
		records, err := model.Where(where).All()
		if err != nil {
			g.Log().Line().Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			list := records.List()
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *alarm) GetAlarmHisPage(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	limit := r.GetInt("limit")
	page := r.GetInt("page")
	order := r.GetString("order")

	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	device_addr := gconv.String(params["device_addr"])
	device_type := gconv.String(params["device_type"])
	sn := gconv.String(params["sn"])
	level := gconv.String(params["level"])
	_type := gconv.String(params["type"])
	subtype := gconv.String(params["subtype"])

	alarm_content := gconv.String(params["alarm_content"])
	hnum := gconv.String(params["hnum"])

	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])

	where := fmt.Sprintf(" sys_name='%s' ", model.SysName)

	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if device_addr != "" {
		where += fmt.Sprintf(" and device_addr='%s'", device_addr)
	}
	if device_type != "" {
		where += " and device_type='" + device_type + "'"
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	if level != "" {
		where += fmt.Sprintf(" and level = %s", level)
	}
	if _type != "" {
		where += fmt.Sprintf(" and type = %s", _type)
	}
	if subtype != "" {
		where += fmt.Sprintf(" and subtype = %s", subtype)
	}
	if hnum != "" {
		where += fmt.Sprintf(" and remark='%s'", hnum)
	}

	if alarm_content != "" {
		where += " and alarm_content LIKE '%" + alarm_content + "%'"
	}

	if begin != "" {
		where += " and add_time>='" + begin + "' "
	}
	if end != "" {
		end += " 23:59:59"
		where += " and add_time<='" + end + "' "
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	//db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		isadmin := dao.IsAdmin(userid)
		if isadmin {
		} else {
			farm_list := dao.GetPermisFarm(userid)
			var farm_id_arr []string
			if len(farm_list) > 0 {
				for _, item := range farm_list {
					farm_id_arr = append(farm_id_arr, gconv.String(item["id"]))
				}
				where += fmt.Sprintf(" and farmid in (%s) ", gstr.Join(farm_id_arr, ","))
			}
			if houseid != "" {
				addrArr := dao.T_device.GetAddrArr("houseid=" + houseid)
				where += fmt.Sprintf(" and device_addr in ('%s')   ", gstr.Join(addrArr, "','"))
			}
			if farmid != "" {
				addrArr := dao.T_device.GetAddrArr("farmid=" + farmid)
				where += fmt.Sprintf(" and device_addr in ('%s')   ", gstr.Join(addrArr, "','"))
			}
		}

		orders := ""
		if order != "" {
			orders = order
		} else {
			orders = " add_time desc "
		}
		//if fields == "" {
		//	fields = "*"
		//}

		var taosDSN = g.Cfg().GetString("taos.connect_str")
		//g.Log().Line(true).Info("DSN:%s", taosDSN)
		taos, err := sql.Open("taosRestful", taosDSN)
		defer taos.Close()
		if err != nil {
			g.Log().Line(true).Errorf("failed to connect TDengine, err:%s", err.Error())
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			sql := fmt.Sprintf("SELECT COUNT(*) as num FROM `t_device_alarm_his` where %s", where)
			g.Log().Line(true).Infof(sql)
			rows, err := taos.Query(sql)
			defer rows.Close()
			if err != nil {
				g.Log().Line(true).Errorf("failed to select from table, err:%s", err.Error())
			} else {

				count := 0
				for rows.Next() {
					var r struct {
						num uint32
					}
					err := rows.Scan(&r.num)
					if err != nil {
						g.Log().Line(true).Error(err)
						break
					}
					count = int(r.num)

				}

				res["count"] = count
				start := limit*page - limit
				if start < 0 {
					start = 0
				}

				sql := fmt.Sprintf("SELECT * FROM `t_device_alarm_his` where %s  order by %s limit %d,%d", where, orders, start, limit)
				g.Log().Line(true).Infof(sql)
				list := tdengine.GetRecordsNew(sql)
				//g.Log().Line(true).Infof(sql)
				for _, item := range list {
					houseid := gconv.Int(item["houseid"])
					lists, _ := dao.V_house.GetList(fmt.Sprintf(" id=%d ", houseid))
					if len(lists) > 0 {
						item["housename"] = lists[0]["housename"]
						item["farmname"] = lists[0]["farmname"]
					}

				}
				res["code"] = 0
				res["data"] = list
			}

		}
	} else {
		res["code"] = -1
		res["msg"] = "Permission denied"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*alarm) GetCurAlarm(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	where := " 1=1 "
	where += " and IFNULL(farmid,'')!='' "
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		where += dao.SetPermisAddWhere(userid)
		records, error := db.Model("v_alarm_now").Where(where).Order(" add_time desc ").All()
		if error != nil {
			g.Log().Line(true).Error(error)
			res["msg"] = error.Error()
			res["code"] = -1
		} else {
			list := records.List()
			res["code"] = 0
			res["data"] = list
			res["count"] = len(list)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*alarm) Delete(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}
	params := r.GetFormMap()
	id := gconv.String(params["id"])
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {

		isok, err := dao.T_alarm.CancelAlarmByUser(id)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			if isok {
				res["code"] = 0
				res["msg"] = ""
			}
		}
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*alarm) GetCurAlarmNum(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	where := " 1=1 "
	where += " and IFNULL(farmid,'')!='' "
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	//db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		//管理员可以看到全部，其他角色按照权限获取
		where += dao.SetPermisAddWhere(userid)
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		num, error := db.Model("v_alarm_now").Where(where).Count()
		if error != nil {
			g.Log().Line(true).Error(error)
			res["msg"] = error.Error()
			res["code"] = -1
			res["count"] = 0
		} else {
			res["code"] = 0
			res["data"] = num
			res["count"] = num
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*alarm) FarmSummary(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		farmid := gconv.String(params["farmid"])
		cmd := fmt.Sprintf(`SELECT count(0) as total_num,SUM(if(level>0,1,0)) as alarm_num,
SUM(if(level=0,1,0)) as notice_num 
FROM v_alarm_now WHERE farmid=%s;`, farmid)
		dt, err := db.GetOne(cmd)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
			data := g.Map{
				"total_num":  0,
				"alarm_num":  0,
				"notice_num": 0,
				"cancel_num": 0,
			}
			res["data"] = data
		} else {
			data := g.Map{
				"total_num":  0,
				"alarm_num":  0,
				"notice_num": 0,
				"cancel_num": 0,
			}
			if dt != nil {
				data = dt.Map()
				if data["total_num"] == nil {
					data["total_num"] = 0
				}
				if data["alarm_num"] == nil {
					data["alarm_num"] = 0
				}
				if data["notice_num"] == nil {
					data["notice_num"] = 0
				}
				if data["cancel_num"] == nil {
					data["cancel_num"] = 0
				}
			}
			//查询已经取消的
			var taosDSN = g.Cfg().GetString("taos.connect_str")
			//g.Log().Line(true).Info("DSN:%s", taosDSN)
			taos, err := sql.Open("taosRestful", taosDSN)
			defer taos.Close()
			if err != nil {
				g.Log().Line(true).Errorf("failed to connect TDengine, err:%s", err.Error())
			} else {
				cmd = fmt.Sprintf("SELECT count(*) as cancel_num FROM t_device_alarm_his WHERE sys_name='%s' and farmid=%s and status=0;", model.SysName, farmid)
				data["cancel_num"] = tdengine.GetCount(cmd)
				data["total_num"] = gconv.Int(data["total_num"]) + gconv.Int(data["cancel_num"])
			}

			res["data"] = data
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}
